/*
* @Description:
* @Version: 2.0
* @Autor: gaowei
* @Date: 2021-04-21 09:14:49
 * @LastEditors: gaowei
 * @LastEditTime: 2021-04-23 09:10:53
*/

const crossSpawn = require('cross-spawn');
function _crossSpawn(...args) {
  return new Promise((resolve, reject) => {
    const child = crossSpawn(...args);
    child.on('error', (...err) => reject(...err))
    child.on('exit', (...args) => reject(...args))
  })
}
const ora = require('ora');
const path = require('path');
const { fsStats, readFile, writeFile, types } = require('./utils');
const { success, error } = require('./utils/logger');
const packages = { 'babel-eslint': '^10.1.0' }
const targetPath = __dirname
console.log(`npm i -s-d ${Object.keys(packages).map(key => `${key}@${packages[key]}`).join(' ')}`)
const _packages = readFile(path.join(process.cwd(), 'package.json')).then(async (filedata) => {
  const file = JSON.parse(filedata);
  const { devDependencies, dependencies } = file;
  const packageNames = Object.keys(packages).forEach((name) => { // 两个环境里面有一个都不要
    if (!(devDependencies[name] && dependencies[name])) dependencies[name] = packages[name];
  });
  await writeFile(path.join(process.cwd(), 'package.json'), JSON.stringify(file, null, 2))
})

const child = crossSpawn('npm', ['list', '-depth', '0'], {
  // stdio: "inherit"
})
console.log(child)
child.stdout.on('data', (data) => {
  console.log(data.toString())
})
// child.on("message", (stdout) => {
//   console.log("message", stdout)
// })
// child.on("error", (...argv) => {
//   console.log("error", argv)
// })
// child.on("exit", (...argv) => {
//   console.log('argv => ',argv)
// })
// process.exit(0);
// const spinner = ora("下载必要依赖").start();

// let result = crossSpawn.sync(`npm i -s-d ${Object.keys(packages).map(key => `${key}@${packages[key]}`).join(" ")}`, { cwd: targetPath, shell: true });
// spinner.stop();
// if (result.status !== 0) {
//   const output = result.output.toString();
//   const stdout = `${output.split("\n").map((str) => {
//     const type = types.find((v) => str.includes(v)) || "info";
//     const logStr = getColor({ str, type });
//     return type === "info" && logStr && `file => ${logStr}` || logStr;
//   }).join("\n")}\n\n\n${getColor({ str: "eslint 失败，请修正后重试", hex: "#ea4d4d" })}\n\n`;
//   error(stdout);
//   error("eslint 失败，请修正后重试");
//   // logger.error('eslint 失败，请修正后重试');
// } else {
//   success("eslint 检查成功！ ");
// }